<template>
  <div>
    <template v-if="!isEcho">
      <el-select v-model="svalue" :size="size" :disabled="disabled" filterable clearable :placeholder="placeholder">
        <i slot="prefix" class="el-input__icon el-icon-notebook-2" />
        <el-option
          v-for="item in dealList"
          :key="item.id"
          :label="item.dealName"
          :value="item.id"
        />
      </el-select>
    </template>
    <template v-if="isEcho && sLabel">
      {{ $t(sLabel) }}
    </template>
  </div>
</template>

<script>
import { findDeal, getDealBase } from '@/api/base/deal/dealBase'
export default {
  props: {
    value: {
      type: String,
      default: ''
    },
    // 项目状态
    dealStatus: {
      type: String,
      default: () => ''
    },
    size: {
      type: String,
      default: () => ''
    },
    // 项目类型
    dealType: {
      type: String,
      default: () => ''
    },
    // 是否开启权限控制
    scopeAuthority: {
      type: String,
      default: () => 'false'
    },
    // 投资主体ID- 如不为空则只查询该投资主体投资过的基金
    investmentId: {
      type: String,
      default: () => ''
    },
    clearable: {
      type: Boolean,
      default: true
    },
    placeholder: {
      type: String,
      default: ''
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    isEcho: {
      type: Boolean,
      default: false,
      desc: '回显label'
    }
  },
  data() {
    return {
      svalue: this.value,
      sLabel: '',
      dealList: []
    }
  },
  watch: {
    value: {
      handler(newVal) {
        this.svalue = newVal
        this.getDealBase()
      },
      deep: true,
      immediate: true
    },
    svalue(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.$emit('input', this.svalue)
        this.$emit('change', this.svalue)
      }
    }
  },
  created() {
    var queryParams = {}
    queryParams.dealType = this.dealType
    queryParams.dealStatus = this.dealStatus
    queryParams.scope = this.scope
    queryParams.scopeAuthority = this.scopeAuthority
    queryParams.investmentId = this.investmentId
    findDeal(queryParams).then(response => {
      this.dealList = response.data
      this.getDealBase()
    })
  },
  methods: {
    getDealBase() {
      var row = this.dealList.find(item => { return item.id === this.value })
      if (row) {
        this.sLabel = row.dealName
      } else {
        this.$nextTick(() => {
          if (!this.isEmpty(this.value)) {
            getDealBase(this.value).then(response => {
              if (response.data) {
                this.dealList.push(response.data)
                var row = this.dealList.find(item => { return item.id === this.value })
                if (row) {
                  this.sLabel = row.dealName
                }
              }
            })
          }
        })
      }
    }
  }
}
</script>
